<template>
  <div class="birthday">
    <van-datetime-picker
      v-model="currentDate"
      type="date"
      title="选择年月日"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="onconfirm"
      @cancel="oncancle"
    />
  </div>
</template>

<script>
import { updateUserInfo } from '@/api/user'
export default {
  name: 'Birthday',
  components: {},
  props: {
    value: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      minDate: new Date(1950, 0, 1),
      maxDate: new Date(2055, 10, 1),
      currentDate: new Date(this.value)
    }
  },
  created() {},
  mounted() {},
  activited() {},
  update() {},
  beforeRouteUpdate() {},
  methods: {
    oncancle() {
      this.$emit('close')
    },
    onconfirm(value) {
      const arr = new Date(value).toLocaleDateString().split('/')
      //   arr = arr.map((item, i) => {
      //     // 补零
      //     if (i > 0) {
      //       return item.padStart(2, '0')
      //     }
      //     return item
      //   })

      //   for (let i = 0, len = arr.length; i < len; i++) {
      //     if (i === 0) continue
      //     arr[i] = arr[i].padStart(2, '0')
      //   }

      arr.forEach((item, i) => {
        if (i > 0) {
          arr[i] = arr[i].padStart(2, '0') // forEach只能通过索引的形式修改值
        }
      })

      const str = arr.join('-')

      this.updateUserInfo(str)
    },

    // 更改生日
    async updateUserInfo(date) {
      if (this.value === date) {
        return this.$toast('未修改')
      }
      try {
        // 1.发请求
        await updateUserInfo({ birthday: date })
        // 2.关弹窗
        this.$emit('close')
        // 3.改视图
        this.$emit('input', date)
        // 4.给提示
        this.$toast.success('更改生日成功')
      } catch (error) {
        this.$toast.success('更改生日失败')
      }
    }
  },
  filter: {},
  computed: {},
  watch: {}
}
</script>

<style lang="less" scoped></style>
